namespace Pp.UI.Binders
{
    using System.Web.Mvc;

    public abstract class ModelBinderBase : System.Web.Mvc.DefaultModelBinder
    {
        public override sealed object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var result = Bind(controllerContext, bindingContext);
            return result;
        }

        protected object BindModelInBase(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            return base.BindModel(controllerContext, bindingContext);
        }

        protected abstract object Bind(ControllerContext controllerContext, ModelBindingContext bindingContext);

        protected void SetModelValue(ModelBindingContext bindingContext, ControllerContext controllerContext)
        {
            var key = bindingContext.ModelName;
            var result = bindingContext.ValueProvider.GetValue(key);

            if ((result != null) && !string.IsNullOrEmpty(result.AttemptedValue))
                bindingContext.ModelState.SetModelValue(key, result);
        }
    }
}